
import { _decorator, Component, Node, find, __private, log, EventTouch, BoxCollider2D, Collider2D, Contact2DType, IPhysics2DContact, JsonAsset, path, Graphics, Vec3, Label, Color, Sprite, color } from 'cc';
import { Actor } from '../../modules/Actor/Actor';
import { ActorBase } from '../../modules/Actor/ActorBase';
import { main } from '../main';
import { ModuleCenter } from '../ModuleCenter';
import { clickBoard } from './clickBoard';
const { ccclass, property } = _decorator;


@ccclass('pvpMain')
export class pvpMain extends Component {
    private static instance: pvpMain;
    public actor: Actor;
    @property({ type: JsonAsset, displayName: "位置点配置" })
    public PVPConfig: JsonAsset = null;
    @property({ type: Graphics, displayName: "绘图组件" })
    public graphics: Graphics = null;
    @property({ type: Label, displayName: "操作名" })
    public operationName: Label = null;



    public PVPConfigData: object;
    public static getInstance() {
        return this.instance;
    }

    public graphicsStart: Vec3 = null;
    public graphicsEnd: Vec3 = null;
    //游戏状态相关变量
    /**
     * 攻击对象
     */
    public currentClickBoard: Node;
    /**
     * 被攻击对象
     */
    public checkedClickBoard: Node;
    public isInAction: boolean = false;;


    private _actors: { actor: ActorBase | null, collisionBlock: Node, type: "role" | "monster" | null }[] = [];


    onLoad() {
        this.initializedState();
        this.init().then(() => {
            //关闭loading
            main.getInstance().offLoading();
        });
    }
    async init() {
        this.PVPConfigData = this.PVPConfig.json;
        let uiNode: Node = find("Canvas/UI");



        //为每个位置设置点击板 并记录怪物和角色的位置
        this.PVPConfigData["actorPoint"].forEach(async (data: object) => {
            let clickBoard = await main.getInstance().loadPublicResources("clickBoard");
            clickBoard.setParent(uiNode);
            let prth: string = data["path"];
            let paths: string[] = prth.split("/");
            let v3 = uiNode.getChildByName(paths[0]).getChildByName(paths[1]).getWorldPosition();
            clickBoard.setWorldPosition(v3);
            this._actors.push({ actor: null, collisionBlock: clickBoard, type: data["type"] });
        });


        //添加碰撞小块  用于检测攻击目标
        let collisionBlockNode = await main.getInstance().loadPublicResources("collisionBlock");
        collisionBlockNode.setParent(uiNode);
        let Collider = collisionBlockNode.getComponent(Collider2D);
        let sprite: Sprite;
        Collider.on(Contact2DType.BEGIN_CONTACT, (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) => {
            if (this.currentClickBoard !== otherCollider.node) {
                this.checkedClickBoard = otherCollider.node;
                this.checkedClickBoard.setSiblingIndex(main.ui.children.length - 1);
                if (sprite != this.checkedClickBoard.getComponent(Sprite)) {
                    sprite = this.checkedClickBoard.getComponent(Sprite);
                }
                sprite.color = new Color(31, 87, 131, 119);
            }
        }, this);
        Collider.on(Contact2DType.END_CONTACT, (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) => {
            if (this.currentClickBoard !== otherCollider.node) {
                this.checkedClickBoard = null;
                sprite.color = new Color(31, 87, 131, 0);
            }
        }, this);

        //注册获取actor模块模块
        let actorNode = await main.getInstance().getModuleNode("Actor");
        actorNode.setParent(this.node);
        //获取actor模块
        this.actor = ModuleCenter.getModule("Actor") as Actor;
        //加载角色

        main.roleList.forEach(async (roleName: string, index: number) => {
            let role = await this.actor.getRole(main.ui, roleName);
            role.showHpBar();
            this._actors[index].actor = role;
            let v3 = this._actors[index].collisionBlock.getWorldPosition();
            role.setLocation(v3);
        });

        //加载怪物
        for (let index = 0; index < 3; index++) {
            let monster = await this.actor.getRandomMonster(main.ui);
            monster.showHpBar();
            this._actors[index + 6].actor = monster;
            let v3 = this._actors[index + 6].collisionBlock.getWorldPosition();
            monster.setLocation(v3);
        }

        //添加事件
        this._actors.forEach(data => {
            if (data.type == "role") {
                data.collisionBlock.on(Node.EventType.TOUCH_START, () => {
                    if (data.actor == null) {
                        return;
                    }
                    this.currentClickBoard = data.collisionBlock;
                    this.graphicsStart = this.currentClickBoard.getWorldPosition();
                });
                data.collisionBlock.on(Node.EventType.TOUCH_MOVE, (e: EventTouch) => {
                    if (data.actor == null) {
                        return;
                    }
                    collisionBlockNode.setWorldPosition(e.getUILocation().x, e.getUILocation().y, 0);
                    if (this.checkedClickBoard === null) {
                        this.graphicsEnd = new Vec3(e.getUILocation().x, e.getUILocation().y, 0);
                        this.operationName.node.active = false;
                    } else {
                        this.graphicsEnd = new Vec3(this.checkedClickBoard.getWorldPosition().x, this.checkedClickBoard.getWorldPosition().y + 200, 0);
                        this.checkedClickBoard
                        this._actors.forEach(data => {
                            if (!this.isInAction) {
                                this.operationName.color = new Color(224, 217, 28, 255);
                                if (data.collisionBlock === this.checkedClickBoard) {
                                    if (data.type === "monster") {
                                        this.operationName.string = "攻击";
                                    } else {
                                        this.operationName.string = "换位";
                                    }
                                }
                            } else {
                                this.operationName.string = "静止操作";
                                this.operationName.color = new Color(255, 0, 0, 255);
                            }

                        });
                        this.operationName.node.active = true;
                    }

                });
                data.collisionBlock.on(Node.EventType.TOUCH_END, () => {
                    if (data.actor == null) {
                        return;
                    }
                    collisionBlockNode.setPosition(0, 0, 0);
                    this.operationName.node.active = false;
                    this.graphicsStart = null;
                    this.graphicsEnd = null;
                    this.initializedState();
                });
                data.collisionBlock.on(Node.EventType.TOUCH_CANCEL, () => {
                    if (data.actor == null) {
                        return;
                    }
                    this.operationName.node.active = false;
                    this.graphicsStart = null;
                    this.graphicsEnd = null;
                    if (this.checkedClickBoard === null) {
                        return;
                    }
                    if (!this.isInAction) {
                        this.isInAction = true;
                        let role: ActorBase;
                        let roleActor: {
                            actor: ActorBase;
                            collisionBlock: Node;
                            type: "role" | "monster";
                        };
                        this._actors.forEach(data => {
                            if (data.collisionBlock === this.currentClickBoard) {
                                role = data.actor;
                                roleActor = data;
                            }
                        });
                        this._actors.forEach(data => {
                            if (data.collisionBlock === this.checkedClickBoard) {
                                if (data.type === "monster") {
                                    if (data.actor === null) {
                                        this.isInAction = false;
                                        return;
                                    }
                                    let monster = data.actor;
                                    role.node.setSiblingIndex(main.ui.children.length - 1);
                                    role.attacks({
                                        v3: monster.node.getPosition(),
                                        attackCompletionCallback: (isInAction: boolean) => {
                                            this.isInAction = isInAction;
                                            console.log(this.isInAction);
                                        }
                                    });
                                    setTimeout(() => {
                                        monster.hit(10);
                                    }, 800);
                                } else {
                                    if (data.actor === null) {
                                        data.actor = role;
                                        role.move({
                                            v3: data.collisionBlock.getPosition(),
                                            attackCompletionCallback: (isInAction: boolean) => {
                                                this.isInAction = isInAction;
                                            }
                                        });
                                        roleActor.actor = null;
                                    } else {
                                        roleActor.actor = data.actor;
                                        data.actor = role;
                                        data.actor.move({
                                            v3: data.collisionBlock.getPosition(),
                                            attackCompletionCallback: (isInAction: boolean) => {
                                                this.isInAction = isInAction;
                                            }
                                        });
                                        roleActor.actor.move({
                                            v3: roleActor.collisionBlock.getPosition(),
                                            attackCompletionCallback: (isInAction: boolean) => {
                                                this.isInAction = isInAction;
                                            }
                                        });

                                    }

                                }
                            }
                        });
                        collisionBlockNode.setPosition(0, 0, 0);
                        this.initializedState();
                    }


                });
            }
        });

    }

    /**
     * 初始化状态相关变量
     */
    initializedState() {
        this.currentClickBoard = null;
        this.checkedClickBoard = null;
    }
    update(deltaTime: number) {
        if (this.graphicsStart != null && this.graphicsEnd != null) {
            this.graphics.clear();
            this.graphics.moveTo(this.graphicsStart.x, this.graphicsStart.y + 200);
            this.operationName.node.setWorldPosition((this.graphicsStart.x + this.graphicsEnd.x) / 2, 400, 0);
            this.graphics.quadraticCurveTo((this.graphicsStart.x + this.graphicsEnd.x) / 2, (this.graphicsStart.x + this.graphicsEnd.x) / 2 + 100, this.graphicsEnd.x, this.graphicsEnd.y);
            this.graphics.stroke();
        } else {
            this.graphics.clear();
        }
    }
}
